package com.yeebo.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;


/**
 * 基于OKHttp构建的请求工具类
 */
public class OKHttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(OKHttpUtils.class);

    public static JSONObject postJson(String url, JSONObject body) {
        OkHttpClient httpClient = new OkHttpClient();

        String bodyStr = body.toString();
        JSONObject responseObj = null;
        logger.info("发送请求url={}，body={}", url, bodyStr);
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), bodyStr);
            Request request = new Request.Builder().url(url).post(requestBody).build();
            Response response = httpClient.newCall(request).execute();
            String result = Objects.requireNonNull(response.body()).string();
            logger.info("接收请求url={}，返回内容={}", url, result);
            responseObj = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("请求url={}报错，错误信息{}", url, e);
        }
        return responseObj;
    }

}
